package server.boot;


import server.mapper.RequestProcessor;
import server.mapper.Server;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;


/**
 * @program: myTomcat_zhenghao
 * @description:
 * @author: Zheng Hao
 * @create: 2020-02-15 11:17
 */
public class BootStrap {
    //存放server
    private Server server;

    /**
     * @Description: 初始化service 对象
     * @param 
     * @Date: 2020/3/31 14:13
     * @Author: wuguizhen
     * @Return void
     * @Throws
     */
    private void initServer() throws Exception{
        server = new Server();
    }

    /**初始化操作*/
    public void start() throws Exception{
        //加载server.xml 初始化
        initServer();
        // 定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize =50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();


        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );
        /*
            完成Minicat 1.0版本
            需求：浏览器请求http://localhost:8080,返回一个固定的字符串到页面"Hello Minicat!"
         */
        ServerSocket serverSocket = new ServerSocket(server.getPort());
        System.out.println("=====>>>Minicat start on port：" + server.getPort());
        //多线程改造（使用线程池）
        while (true) {
            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket,server);
            threadPoolExecutor.execute(requestProcessor);
        }
    }
    /**mytomcat 程序入口*/
    public static void main(String[] args) throws Exception {
        BootStrap bootStrap = new BootStrap();
        bootStrap.start();

    }
}
